class Message < ActiveRecord::Base
  #has_and_belongs_to_many :users
  has_many :user_messages, :dependent => :destroy
  has_many :users, :through => :user_messages
  
  validates_presence_of     :title, :message => "标题不能为空"
  validates_presence_of     :content, :message => "内容不能为空"
  validates_length_of       :title,    :within => 3..50, :too_long => "标题在3到50位之间", :too_short => "标题在3到50位之间"
  
  def can_delete?
    query = ""
    query << "select count(*) as num"
    query << " from messages, user_messages"
    query << " where messages.id = user_messages.message_id"
    query << " and user_messages.message_id = '"
    query << self.id.to_s
    query << "'"
    messages = Message.find_by_sql [query]
    messages[0].num.to_i == 1
  end
  
  def before_save
    self.title = self.title.gsub(/^\<(script|frame)/i, '')
    self.content = self.content.gsub(/^\<(script|frame)/i, '')
  end
end
